import axios from "axios"

export default {
  namespaced: true,
  state(){
    return {
      list: []
    }
  },
  getters: {
    total(state) {
      return state.list.reduce((p, c) => p + c.count, 0);
    },
    totalPrice (state) {
      return state.list.reduce((p, c) => p + c.count * c.price, 0);
    },
  },
  mutations: {
    updateList(state, list){
      state.list = list
    },
    changeCount(state, {id, count}){
      const item = state.list.find(item => item.id === id)
      if(item){
        item.count = count
      }
    }
  },
  actions: {
   async getList(context){
      const res = await axios.get('http://localhost:3000/cart')
      console.log(res)
      context.commit('updateList', res.data)
    },
   async  updateCount(context, payload){
      await axios.patch(`http://localhost:3000/cart/${payload.id}`, {
        count: payload.count
      })
      // 提交mutation, 修改state中的数据
      context.commit('changeCount', payload)
    }
  }
}